﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MusicStore.Entities;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Linq;

namespace MusicStore.Data.Repository
{
	/// <summary>
	/// repository implemented using NHibernate and linq to NHibernate, it's a very basic implemtation
	/// </summary>
	public class AlbumRepository : RepositoryBase, IAlbumRepository
	{
		#region IAlbumRepository Members

		public IQueryable<Album> Albums()
		{
			return Session.Linq<Album>();
		}

		public IQueryable<AlbumSummary> AlbumSummaries()
		{
			return Session.Linq<AlbumSummary>();
		}

		public IQueryable<Genre> Genres()
		{
			return Session.Linq<Genre>();
		}

		public IQueryable<Label> Labels()
		{
			return Session.Linq<Label>();
		}

		public IQueryable<Author> Authors()
		{
			return Session.Linq<Author>();
		}

		public void Save(Album album)
		{
			Session.SaveOrUpdate(album);

			// perform addictional steps like adding data to the genre, label and authors if not present

			// add the author if not in the list
			if (Authors().FirstOrDefault(g => g.Name == album.Author) == null)
				Save(new Author { Name = album.Author });
			// add the genre if not in the list
			if (Genres().FirstOrDefault(g => g.Name == album.Genre) == null)
				Save(new Genre { Name = album.Genre });
			// add the label if not in the list
			if (Labels().FirstOrDefault(g => g.Name == album.Label) == null)
				Save(new Label { Name = album.Label });
		}

		public void Delete(Album album)
		{
			Session.Delete(album);
		}

		#endregion
	}
}
